<template>
  <div class="" style="background-color: #ffffff;padding: 8px">
    <!-- <el-card shadow="never">
      <div slot="header" style="text-align: center;">门店列表</div> -->
    <div>
      <div style="padding: 10px 0">
        <el-button type="success" size="large" @click="addmodel">添加</el-button>
      </div>
      <div class="tableClass">
        <!-- v-loading="loading" -->
        <el-table :data="formdata" :header-cell-style="{background:'#eef1f6',color:'#606266'}" border style="width: 100%;">
          <el-table-column align="center" prop="id" label="序号" />
          <el-table-column align="center" prop="name" label="门店头像">
            <template slot-scope="scope">
              <!-- <div @click="showTaskModel(scope.row)" style="cursor:pointer;color:#409EFF">{{scope.row.task_name}}</div> -->
              <el-button type="text" size="medium">
                <img style="width: 50%;" :src="scope.row.logo_img_Url" />
              </el-button>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="name" label="门店名称">
            <template slot-scope="scope">
              <!-- <div @click="showTaskModel(scope.row)" style="cursor:pointer;color:#409EFF">{{scope.row.task_name}}</div> -->
              <el-button type="text" size="medium" @click="storeDetail(scope.row,scope.row.id)">
                {{scope.row.name}}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="addressAll" label="地址" />
          <el-table-column align="center" prop="contact" label="电话" />
          <el-table-column align="center" prop="newtime" label="营业时间">
            <template slot-scope="scope">
              <div v-if="scope.row.newtime != 'null-null'">{{scope.row.newtime}}</div>
              <div v-else>未设置</div>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="status_name" label="营业状态">
           <template slot-scope="scope">
             <el-select v-model="scope.row.status" @change="changeMerchantStatus(scope.row.id,scope.row.status)">
               <el-option v-for="opt in options" :key="opt.id" :value="opt.id" :label="opt.label" />
             </el-select>
           </template>
         </el-table-column>
          <!--<el-table-column align="center" prop="newtime" label="营业状态">
            <template slot-scope="scope">
              <el-tag style="cursor: pointer" :type="scope.row.status==0?'primary':'success'" @click="changeMerchantStatus(scope.row.id,scope.row.status)">{{scope.row.status_name}}</el-tag>
            </template>
          </el-table-column>-->
          <el-table-column align="center" prop="support_delivery_method" label="配送方式">
            <template slot-scope="scope">
              <el-button type="text" @click="DeliveryModelTan(scope.row)">{{scope.row.deliveryWay}}</el-button>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="250px">
            <template slot-scope="scope">
              <!--<router-link style="margin-bottom: 10px;" :to="{path:'/storeManage/store_list/store_one',query: {row: scope.row.id,row2:scope.row.name}}"
                           tag="div">
                <el-button type="primary" size="mini" @click="removItem">
                  管理
                </el-button>
              </router-link>-->
              <el-button type="warning" size="mini" @click="updateMsg(scope.row)">编辑</el-button>
              <el-button type="danger" size="mini" @click="delMsg(scope.row.id)">删除</el-button>
              <div style="margin-top: 8px">
                <el-button type="success" size="mini" @click="showMerchantQrCode(scope.row)">门店二维码</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <br>
        <!-- 分页 -->
        <div style="text-align: center;">
          <el-pagination background layout="prev, pager, next" @current-change="pageChange" :page-size="pageSize"
                         :total="totalusers" />
        </div>
      </div>
      <!-- </el-card> -->

      <!-- 模态款-->
      <div>
        <!-- 添加模态款 -->
        <el-dialog :title="title" :visible.sync="modelMsg">
          <div class="msgDiv">
            <div>
              <el-form ref="form" :model="form" label-width="100px">
                <el-form-item label="序号" v-show="vshow">
                  <el-input v-model="form.id" placeholder="序号" disabled></el-input>
                </el-form-item>
                <el-form-item label="门店名称" :required="true">
                  <el-input v-model="form.name" placeholder="请输入门店名称"></el-input>
                </el-form-item>
                <el-form-item label="联系方式" :required="true">
                  <el-input v-model="form.contact" placeholder="请输入联系方式"></el-input>
                </el-form-item>
                <!-- <el-form-item label="营业时间">
                <el-input v-model="form.business_time" placeholder="请输入营业时间"></el-input>
              </el-form-item> -->
                <el-form-item label="营业时间" style="text-align: left;">
                  <el-time-picker style="width: 100%;" is-range v-model="newtime" value-format="HH:mm:ss"
                                  range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围">
                  </el-time-picker>
                  <!-- <el-date-picker class="oldInputTime" v-model="newtime" value-format="yyyy-MM-dd HH:mm:ss" type="datetimerange"
                  range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
                </el-date-picker> -->
                </el-form-item>
                <el-form-item label="所在地址" prop="origin" style="text-align: left;">
                  <!-- <el-cascader placeholder="选择所在的地址" :options="ORIGIN" :props="{value:'label'}" v-model="addressList"
                  filterable></el-cascader> -->

                  <div>
                    <el-autocomplete style="width: 80%;margin-right: 10px;" class="inline-input" v-model="form.address"
                                     :fetch-suggestions="watchInput" placeholder="请输入内容" :trigger-on-focus="false" @select="handleSelect"></el-autocomplete>
                    <!-- <el-button @click="searchBtn(form.address)">搜索</el-button> -->
                    <div id="container"></div>
                  </div>
                </el-form-item>
                <!-- <el-form-item label="详细地址">
                <el-input v-model="form.address" placeholder="请输入详细街道地址"></el-input>
              </el-form-item> -->
                <div style="text-align: left;">
                  <el-form-item label="门店头像" style="color: black;">
                    <el-tooltip placement="top">
                      <div slot="content">请上传门店的招牌图片</div>
                      <i class="el-icon-info" style="font-size: 18px;"></i>
                    </el-tooltip>
                    <el-upload class="avatar-uploader" :action="$api.UPLOAD_IMG" name='photo'
                               :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                      <div v-if="imageUrl">
                        <img :src="imageUrl" class="avatar" @mouseover="showDelPic = true">
                        <i v-show="showDelPic" @click.stop="removeDel" @mouseleave="showDelPic=false" class="el-icon-delete deleteClass"></i>
                      </div>

                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>

                  </el-form-item>
                </div>
                <el-button type="success" @click="addMsg(form)">{{addORupdate}}</el-button>

              </el-form>

            </div>
          </div>
        </el-dialog>

        <!-- 配送方式model -->
        <el-dialog title="配送方式" class="businessDialog" :visible.sync="DeliveryModel">
          <div class="msgDiv">
            <div>
              <el-input v-model="deliveryForm.id" v-show="false" disabled></el-input>
              <div style="margin-bottom: 20px;">
                <div class="checkboxLeft">
                  <el-checkbox v-model="checked1" label="自提"></el-checkbox>
                </div>

                <div class="checkboxLeft">
                  <el-checkbox label="快递" v-model="checked2"></el-checkbox>
                  <!-- 快递输入 -->
                  <div v-if="checked2==true" style="display: flex;padding: 20px;">
                    <span class="checkSpan">快递费</span>
                    <el-input v-model="deliveryAll.expressMoney" placeholder="单位:元"></el-input>
                  </div>
                </div>

                <div class="checkboxLeft">
                  <el-checkbox label="即时配送" v-model="checked3"></el-checkbox>
                  <!-- 即时配送 -->
                  <div v-if="checked3==true">
                    <div style="display: flex;padding: 20px;">
                      <span class="checkSpan">配送范围</span>
                      <el-input v-model="deliveryAll.scope" placeholder="单位:KM"></el-input>
                    </div>
                    <div style="display: flex;padding: 20px;">
                      <span class="checkSpan">起送</span>
                      <el-input v-model="deliveryAll.step" placeholder="单位:元"></el-input>
                    </div>
                    <div style="display: flex;padding: 20px;">
                      <span class="checkSpan">配送费</span>
                      <el-input v-model="deliveryAll.fee" placeholder="单位:元"></el-input>
                    </div>
                  </div>
                </div>

              </div>

              <el-button type="success" @click="SubmitDelivery()">添加</el-button>
            </div>
          </div>
        </el-dialog>
        <!-- 门店详细 model -->
        <el-dialog title="门店详细" class="businessDialog" :visible.sync="businessModel">
          <div class="businessCss">
            <el-form style="font-size: 20px;">
              <el-form-item label="门店ID:" label-width="120px">
                <span>{{storeDetailAll.id}}</span>
              </el-form-item>
              <el-form-item label="门店头像:" label-width="120px">
                <span><img width="45%" :src="storeDetailAll.logo_img_Url"></img></span>
              </el-form-item>
              <el-form-item label="门店名称:" label-width="120px">
                <span>{{storeDetailAll.name}}</span>
              </el-form-item>
              <el-form-item label="详细地址:" label-width="120px">
                <span>{{addressDetail}}</span>
              </el-form-item>
              <el-form-item label="联系方式:" label-width="120px">
                <span>{{storeDetailAll.contact}}</span>
              </el-form-item>
              <el-form-item label="营业时间:" label-width="120px">
                <span>{{newtime}}</span>
              </el-form-item>
              <el-form-item label="配送方式:" label-width="120px">
                <span>{{deliveryWay}}</span>
              </el-form-item>
              <el-form-item label="快递邮费:" label-width="120px">
                <span>{{deliveryAll.expressMoney}} 元</span>
              </el-form-item>
              <el-form-item label="配送范围:" label-width="120px">
                <span>{{deliveryAll.scope}} 千米</span>
              </el-form-item>
              <el-form-item label="起送:" label-width="120px">
                <span>{{deliveryAll.step}} 元</span>
              </el-form-item>
              <el-form-item label="配送费:" label-width="120px">
                <span>{{deliveryAll.fee}} 元</span>
              </el-form-item>
              <el-form-item label="营业状态:" label-width="120px">
                <el-tag type="warning" style="width: 20%;text-align: center;">{{storeDetailAll.status_name}}</el-tag>
              </el-form-item>
              <el-form-item label="创建时间:" label-width="120px">
                <span>{{storeDetailAll.created_at}}</span>
              </el-form-item>
            </el-form>
          </div>
          <div slot="footer" class="dialog-footer" style="text-align: center;">
            <el-button type="primary" @click="businessModel = false">确 定</el-button>
          </div>
        </el-dialog>
      </div>
    </div>

    <!-- 展示图片 -->
    <el-dialog :title="'门店二维码'" :visible.sync="imgDialogShow" >
      <el-form :label-position="'left'" label-width="150px">
        <div align="center" v-if="merchantQrCode">
          <el-image lazy :src="merchantQrCode" alt="" style="max-width:400px;margin:0 auto"></el-image>
        </div>
      </el-form>
      <div style="text-align: center">
        <el-button @click="downloadMerchantQrCode()" type="primary">下载</el-button>
      </div>
    </el-dialog>
    <!-- 展示图片 -->

  </div>
</template>

<script>
  // import ORIGIN from '../../assets/json/origin.json'
  //地图组件---按需引入
  export default {
    data() {
      return {
        // ORIGIN,
        form: {
          id: "",
          name: "",
          logo_img_id: "",
          // province: "",
          // city: "",
          // area: "",
          lng: "",
          lat: "",
          address: "",
          contact: "",
          // business_time: "",
          business_start_time: "",
          business_end_time: ""
          /* status: "" */
        },
        detailShow: undefined,
        showMapComponent: this.value,
        keyword: '',
        deliveryForm: {
          id: "",
          delivery_method: []
        },
        deliveryAll: {
          expressMoney: "",
          scope: "",
          step: "",
          fee: "",
        },
        options: [{
          id: 0,
          label: "休息中"
        }, {
          id: 1,
          label: "正常营业"
        },
          /* {
            id: '2',
            label: "关闭门店"
          } */
        ],
        checked1: false,
        checked2: false,
        checked3: false,
        newtime: "",
        addressList: [],
        storeDetailAll: [],
        addressDetail: "",
        deliveryWay: "",
        value: "",
        title: "",
        imageUrl: "",
        showDelPic: false,
        DeliveryModel: false,
        businessModel: false,
        vshow: false,
        addORupdate: "",
        modelMsg: false, //模态款
        loading: false, //加载中
        formdata: [],
        formdataSecond: [],
        totalusers: 0, //总页数
        pageSize: 10, //每页几行
        startpage: 1, //起始页
        mapList: [],
        // mapAll: [],
        mapVal: '',
        imgDialogShow: false,
        merchantQrCode: '',
        merchantName: ''
      }
    },
    watch: {
      modelMsg(newVal, oldVal) {
        console.log(newVal)
        if (newVal == true) {
          if(this.form.id==0){
            this.initMap(23.12908, 113.26436)
          }
          // if(this.form.id>0){
          //   console.log("大于0")
          //   this.initMap(this.form.lat, this.form.lng)
          // }
        }

      }
    },
    created() {
      // this.initMap(23.12908, 113.26436)
      this.detailShow = this.$route.query.row
      this.getMerchantList()
    },
    methods: {

      //展示商店二维码
      async showMerchantQrCode(item) {
        let id = item.id
        this.merchantName = item.name
        this.merchantQrCode = ''
        this.imgDialogShow = true
        let token = window.localStorage.getItem('user_token')
        this.merchantQrCode = this.$api.baseUrl + 'merchant/getMerchantQrCode?merchant_id='+id + '&merchant_token=' + token
        let res = await this.$api.getMerchantQrCode({
          merchant_id: id
        })
      },

      //选择触发函数
      handleSelect(item) {
        // console.log(item)
        this.form.lat = item.location.lat
        this.form.lng = item.location.lng
        this.initMap(item.location.lat, item.location.lng)
      },
      watchInput(queryString, cb) {
        this.mapList = []
        console.log(queryString)
        const KEY = "5B2BZ-O6UHW-ASRRZ-OE6AU-2L7VF-HKFR4";
        let url = "https://apis.map.qq.com/ws/place/v1/suggestion"
        let keyword = queryString //传入的关键词
        this.$jsonp(url, {
          key: KEY,
          region: "全国",
          keyword: keyword,
          output: "jsonp"
        }).then(res => {
          let opt = []
          res.data.forEach(res => {
            let opt1 = {
              "value": res.title + "-" + res.address,
              "location": res.location
            }
            opt.push(opt1)
          })
          this.mapList = opt
          console.log(this.mapList)
          // 调用 callback 返回建议列表的数据
          cb(this.mapList);
        }).catch(err => {
          console.log(err)
        })
      },
      // searchBtn(val) {
      //   const KEY = "5B2BZ-O6UHW-ASRRZ-OE6AU-2L7VF-HKFR4";
      //   let url = "https://apis.map.qq.com/ws/place/v1/search"
      //   let keyword = val
      //   this.$jsonp(url, {
      //     key: KEY,
      //     boundary: "region(全国)",
      //     keyword: keyword,
      //     output: "jsonp"
      //   }).then(res => {
      //     console.log(res.data)
      //     this.mapAll = res.data
      //     console.log(this.mapList)
      //   }).catch(err => {
      //     console.log(err)
      //   })

      // },
      //初始化地图
      initMap(lat, lng) {
        //如果地图存在，就销毁，下面会重新创建一个
        if (this.mapVal) {
          this.mapVal.destroy()
        }
        //定义地图中心点坐标
        this.$nextTick(() => {
          var center = new window.TMap.LatLng(lat, lng)
          //定义map变量，调用 TMap.Map() 构造函数创建地图
          // let nnn =  document.getElementById('newop')
          //  console.log(nnn)
          this.mapVal = new TMap.Map(document.getElementById('container'), {
            center: center, //设置地图中心点坐标
            zoom: 17.2, //设置地图缩放级别
            pitch: 43.5, //设置俯仰角
            rotation: 45, //设置地图旋转角度
            viewMode: '2D',
            mapStyleId: "style1" ,//个性化样式

          });
          //初始化marker
          var marker = new TMap.MultiMarker({
            id: "marker-layer", //图层id
            map: this.mapVal,
            styles: { //点标注的相关样式
              "marker": new TMap.MarkerStyle({
                "width": 25,
                "height": 35,
                "anchor": {
                  x: 16,
                  y: 32
                },
                "src": "https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/markerDefault.png"
              })
            },
            geometries: [{ //点标注数据数组
              "id": "demo",
              "styleId": "marker",
              "position": new TMap.LatLng(lat, lng),
              "properties": {
                "title": "marker"
              }
            }]
          });
        })
      },
      removItem() {
        window.localStorage.removeItem("activeName")
      },
      removeDel() {
        this.imageUrl = ""
        this.form.logo_img_id = 0
        // this.showDelPic = false
      },
      handleRemove(file, fileList) {
        console.log(file, fileList)
      },

      //确认改变营业状态框
      async confirmChangeMerchantStatus(id, status) {
        await this.$confirm('是否切换营业状态?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          this.changeMerchantStatus(id,status)
        }).catch(() => {

        })
      },

      //改变营业状态
      changeMerchantStatus(id, status) {
        console.log(status)
        /*let statusTemp = status==0?1:0*/
        let params = {
          "id": id,
          "status": status
        }
        this.$api.changeMerchantStatus(params).then(res => {
          console.log(res)
          this.$message({
            type: res.data.level,
            message: res.data.message
          });
          this.getMerchantList()
        })
      },
      //配送方式
      SubmitDelivery() {
        this.deliveryForm.delivery_method = []
        if (this.checked1 == true) {
          let self_pick = [
            "self_pick"
          ]
          this.deliveryForm.delivery_method.push(self_pick)
        }
        if (this.checked2 == true) {
          let express_delivery = [
            "express_delivery", this.deliveryAll.expressMoney
          ]
          this.deliveryForm.delivery_method.push(express_delivery)
        }
        if (this.checked3 == true) {
          let instant_delivery = [
            "instant_delivery", this.deliveryAll.scope, this.deliveryAll.step, this.deliveryAll.fee
          ]
          this.deliveryForm.delivery_method.push(instant_delivery)
        }
        console.log(this.deliveryForm)
        const loadingOne = this.$loading({
          lock: true,
          text: '保存中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        this.$api.setMerchantDeliveryMethod(this.deliveryForm).then(res => {
          console.log(res)
          this.$message({
            type: res.data.level,
            message: res.data.message
          });
          if (res.data.level == "success") {
            this.getMerchantList()
            loadingOne.close()
            this.DeliveryModel = false
          } else {
            this.DeliveryModel = true
            loadingOne.close()
          }
        })
      },
      //配送方式设置弹框
      DeliveryModelTan(row) {
        console.log(row)
        this.checked1 = false
        this.checked2 = false
        this.checked3 = false

        this.deliveryAll = {
          expressMoney: "",
          scope: "",
          step: "",
          fee: "",
        }
        this.deliveryForm.id = row.id
        console.log(this.deliveryForm.id)
        this.DeliveryModel = true
        this.formdataSecond.forEach(res => {
          if (res.id == row.id) {
            console.log(res)
            res.merchant_delivery_method.forEach(item => {
              console.log(item)
              if (item.length == 1) {
                this.checked1 = true
              }
              if (item.length == 2) {
                this.checked2 = true
                this.deliveryAll.expressMoney = item[1]
              }
              if (item.length == 4) {
                this.checked3 = true
                this.deliveryAll.scope = item[1]
                this.deliveryAll.step = item[2]
                this.deliveryAll.fee = item[3]
              }
            })

          }
        })
      },
      //显示门店详细
      storeDetail(row, id) {
        this.deliveryAll = {
          expressMoney: "",
          scope: "",
          step: "",
          fee: "",
        }
        this.businessModel = true
        let dataid = {
          "id": id
        }
        this.deliveryWay = row.deliveryWay
        this.$api.getMerchantDetail(dataid).then(res => {
          this.storeDetailAll = res.data.data
          this.newtime = this.storeDetailAll.business_start_time + "-" + this.storeDetailAll.business_end_time
          // this.addressDetail = this.storeDetailAll.province + "/" + this.storeDetailAll.city + "/" + this.storeDetailAll
          //   .area + "/" + this.storeDetailAll.address
          this.addressDetail = this.storeDetailAll.address
          if (this.storeDetailAll.merchant_delivery_method.length == 0) {
            this.deliveryAll.expressMoney = "（未设置快递）"
            this.deliveryAll.scope = "（未设置即时配送）"
            this.deliveryAll.step = "（未设置即时配送）"
            this.deliveryAll.fee = "（未设置即时配送）"
          }
          this.storeDetailAll.merchant_delivery_method.forEach(item => {
            if (item.length == 2) {
              this.deliveryAll.expressMoney = item[1]
            } else {
              this.deliveryAll.expressMoney = "（未设置快递）"
            }
            if (item.length == 4) {
              this.deliveryAll.scope = item[1]
              this.deliveryAll.step = item[2]
              this.deliveryAll.fee = item[3]

            } else {
              this.deliveryAll.scope = "（未设置即时配送）"
              this.deliveryAll.step = "（未设置即时配送）"
              this.deliveryAll.fee = "（未设置即时配送）"
            }
          })
        })


      },
      //删除店铺信息
      async delMsg(id) {
        let delid = {
          id: id
        }
        await this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          const loadingOne = this.$loading({
            lock: true,
            text: '保存中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          this.$api.delMerchant(delid).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            if (res.data.level == "success") {
              loadingOne.close()
              this.getMerchantList()
            } else {
              this.$message.error(res.data.message)
              loadingOne.close()
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      addmodel() {
        this.modelMsg = true
        this.title = '添加门店信息'
        this.addORupdate = "添加",
          this.vshow = false
        this.form.id = "",
          this.form.name = "",
          this.form.logo_img_id = "",
          this.form.province = "",
          this.form.city = "",
          this.form.area = "",
          this.form.address = "",
          this.form.contact = "",
          this.form.lng = "",
          this.form.lat = "",
          // this.form.business_time = ""
          this.form.business_start_time = ""
        this.form.business_end_time = ""
        this.imageUrl = ""
        this.addressList = []
        this.newtime = ""
      },
      async addMsg(form) {
        console.log(form)
        //判断带星号的是否为空
        /*let checkPhoneResult = this.checkPhone(form.contact)
        if (!checkPhoneResult) return false;*/

        if (form.name == "") {
          this.$message({
            message: "带星号为必填项，请完善信息！",
            type: "warning"
          })
          return false;
        }
        //时间赋值
        this.form.business_start_time = this.newtime[0]
        this.form.business_end_time = this.newtime[1]
        //地址赋值
        // this.form.province = this.addressList[0]
        // this.form.city = this.addressList[1]
        // this.form.area = this.addressList[2]
        /* 显示加载中。。。 */
        const loadingOne = this.$loading({
          lock: true,
          text: '保存中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        if (form.id > 0) {
          /* 修改 */
          console.log(form)
          await this.$api.setMerchant(form).then(res => {
            console.log(res)
            this.$message({
              type: res.data.level,
              message: res.data.message
            });
            if (res.data.level == "success") {
              this.getMerchantList()
              loadingOne.close()
              this.modelMsg = false
            } else {
              this.modelMsg = true
              loadingOne.close()
            }

          })
        } else {
          /* 添加 */
          await this.$api.setMerchant(form).then(res => {
            this.$message({
              type: res.data.level,
              message: res.data.message
            });
            if (res.data.level == "success") {
              this.getMerchantList()
              loadingOne.close()
              this.modelMsg = false
            } else {
              this.modelMsg = true
              loadingOne.close()
            }

          })
        }
        this.modelMsg = false

      },
      //修改弹出框
      updateMsg(row) {
        console.log(row)
        this.newtime = []
        this.modelMsg = true
        this.title = '修改门店信息'
        this.addORupdate = "修改",
          this.vshow = true
        this.form.id = row.id,
          this.form.name = row.name,
          this.form.contact = row.contact
        // this.form.business_time = row.business_time
        //时间
        // let timefirst = row.business_time.split("-")
        this.newtime.push(row.business_start_time)
        this.newtime.push(row.business_end_time)
        this.form.logo_img_id = row.logo_img_id,
          this.imageUrl = row.logo_img_Url,
          this.form.address = row.address
        this.form.lat = row.lat
        this.form.lng = row.lng
        let item = {
          value:this.form.address,
          location:{
            lat:this.form.lat,
            lng:this.form.lng
          }
        }
        this.handleSelect(item)
        //   this.addressList = []
        // this.addressList = row.pro.split("/")

      },
      //获取分页列表
      async getMerchantList() {
        this.loading = true
        let params = {
          "page": this.startpage,
          "limit": this.pageSize,
        }
        //调用后台提供的接口方法
        Array.prototype.contains = function(obj) {
          var index = this.length;
          while (index--) {
            if (this[index] === obj) {
              return true;
            }
          }
          return false;
        }
        await this.$api.getMerchantList(params).then(res => {
          /* console.log(res.data.data) */
          let formOne = []
          if (res.data.level == "success") {
            let data = ""
            for (let i = 0; i < res.data.data.length; i++) {
              data = res.data.data[i]
              let pro = data.province + '/' + data.city + '/' + data.area
              let peiname = ""
              if (data.merchant_delivery_method.length == 0) {
                peiname += "未设置"
              }
              data.merchant_delivery_method.forEach(item => {

                if (item.contains("self_pick")) {
                  peiname += "自提、"
                }
                if (item.contains("express_delivery")) {
                  peiname += "快递、"
                }
                if (item.contains("instant_delivery")) {
                  peiname += "即时配送"
                }
              })
              let msg = {
                id: data.id,
                logo_img_id: data.logo_img_id,
                logo_img_Url: data.logo_img_Url,
                name: data.name,
                contact: data.contact,
                // business_time: data.business_time,
                business_start_time: data.business_start_time,
                business_end_time: data.business_end_time,
                newtime: data.business_start_time + "-" + data.business_end_time,
                status_name: data.status_name,
                pro: pro,
                address: data.address,
                // addressAll: pro + "/" + data.address,
                addressAll: data.address,
                status: parseInt(data.status),
                deliveryWay: peiname,
                lat: data.lat,
                lng: data.lng
              }

              formOne.push(msg)
            }
            this.formdata = formOne
            console.log(this.formdata)
            this.formdataSecond = res.data.data //第二个formdata
            this.totalusers = res.data.page_info.total
            this.loading = false
          }else {
            this.$message.error(res.data.message)
            this.loading = false
          }

        })
      },
      // 手机号码验证 11位数字
      checkPhone(phoneNumb) {
        var user = /^1[0-9]{10}$/
        if (!user.test(phoneNumb)) {
          this.$message({
            message: '手机号码格式错误！',
            type: 'warning'
          });
          return false
        }

        return true
      },
      //分页 pageChange当前页发生改变触发函数
      async pageChange(page) {
        this.startpage = page
        //调用获取列表的方法
        this.loading = true
        this.getMerchantList()
      },
      //图片上传
      handleAvatarSuccess(res, file) {
        //console.log(res.data.id)
        this.form.logo_img_id = res.data.id
        //console.log(file)
        this.imageUrl = res.data.img_url;
      },
      //验证图片格式
      beforeAvatarUpload(file) {
        // const isJPG = file.type === 'image/jpeg';
        // const isLt2M = file.size / 1024 / 1024 < 2;

        // if (!isJPG) {
        //   this.$message.error('上传头像图片只能是 JPG 格式!');
        // }
        // if (!isLt2M) {
        //   this.$message.error('上传头像图片大小不能超过 2MB!');
        // }
        // return isJPG && isLt2M;
      },

      //下载门店二维码
      downloadMerchantQrCode() {
        let image = new Image();
        image.setAttribute("crossOrigin", "anonymous");
        image.src = this.merchantQrCode;
        image.onload = () => {
          let canvas = document.createElement("canvas");
          canvas.width = image.width;
          canvas.height = image.height;
          let ctx = canvas.getContext("2d");
          ctx.drawImage(image, 0, 0, image.width, image.height);
          canvas.toBlob((blob) => {
            let url = URL.createObjectURL(blob);
            this.download(url, this.merchantName+'二维码');
            // 用完释放URL对象
            URL.revokeObjectURL(url);
          });
        };
      },

      download(fileUrl, fileName) {
        let eleLink = document.createElement("a");
        eleLink.download = fileName;
        eleLink.href = fileUrl;
        eleLink.click();
        eleLink.remove();
      },

    }
  }
</script>
<style scoped="scoped">
  /deep/.el-card__header {
    background-color: #409EFF;
    color: whitesmoke;
  }
  /deep/.el-dialog{
    margin-top:2vh !important;
  }

  .msgDiv {
    width: 80%;
    margin: auto;
    text-align: center;
  }

  /* model */
  .businessDialog /deep/.el-dialog__title {
    font-size: 26px;
    text-align: center;
    font-weight: bold;
  }

  .businessDialog /deep/.el-dialog__body {
    padding: 30px 50px;
    background-color: #dddddd57;
  }

  .businessDialog /deep/.el-dialog {
    margin-top: 20px !important;
    margin-bottom: 5px;
    width: 33%;
  }

  .businessCss .msgDiv {
    width: 80%;
    margin: auto;
    text-align: center;
  }
  .el-form-item{
    margin-bottom: 20px;
  }
  .businessCss /deep/.el-form-item__label {
    font-size: 20px !important;
    text-align: right !important;
  }

  .businessCss /deep/.el-form-item__content {
    font-size: 20px !important;
  }

  /* 任务详细CSS */
  .taskWarp /deep/.el-form-item {
    margin-left: 15px;
  }

  .taskWarpTitle /deep/.el-dialog__title {
    font-size: 22px;
  }

  .taskWarp /deep/.el-form-item__label {
    font-size: 18px;
  }

  .taskCss {
    margin-left: 30px;
    margin-right: 30px;
    font-size: 16px;
    background-color: #dddddd57;
    text-align: left;
    padding: 10px 30px 10px 30px;
    margin-bottom: 10px;
    border-radius: 10px;
  }

  .taskCss span.title {
    font-weight: bold;
  }

  .taskCss span.name {
    color: #e21515eb;
  }

  .taskName {
    font-size: 22px;
    color: #e21515eb;
    background-color: #dddddd57;
    display: inline-block;
    padding: 5px 12px 5px 12px;
    font-weight: bold;
    font-family: serif;
    border-radius: 5px;
  }

  .indentLeft {
    margin-left: 26px;
  }

  .requiredCSS {
    margin-left: 30px;
    margin-right: 30px;
    background-color: #dddddd57;
    border-radius: 10px;
    padding: 10px 30px 10px 30px;
  }

  /deep/.edui-editor-imagescale {
    top: 130px !important;
  }

  /* 图片上传css */
  .avatar-uploader /deep/.el-upload {
    border: 1px dashed #807979;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }

  .deleteClass {
    position: absolute;
    top: 0px;
    right: 0px;
    font-size: 16px;
    width: 25px;
    height: 25px;
    line-height: 25px;
    text-align: center;
    background: #00000066;
    color: #e4dcdc;
  }

  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }


  /* 选择框*/
  .checkboxLeft {
    text-align: left;
    margin-bottom: 15px;
  }

  /deep/.el-checkbox__inner {
    /* width: 18px;
    height: 18px; */
  }

  /deep/.el-checkbox__label {
    font-size: 16px;
  }

  .checkSpan {
    width: 200px;
    display: inline-block;
    line-height: 40px;
    font-size: 16px;
    text-align: right;
    margin-right: 10px;
  }

  /* 地图样式 */
  .serachinput {
    width: 300px;
    box-sizing: border-box;
    padding: 9px;
    border: 1px solid #dddee1;
    line-height: 20px;
    font-size: 16px;
    height: 38px;
    color: #333;
    position: relative;
    border-radius: 4px;
    -webkit-box-shadow: #666 0px 0px 10px;
    -moz-box-shadow: #666 0px 0px 10px;
    box-shadow: #666 0px 0px 10px;
  }

  #container {
    /*地图(容器)显示大小*/
    width: 100%;
    height: 400px;
  }
</style>
